package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiPayPlanEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.PayPlanDao;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/25 15:28
 * @since v1.0
 */
@Service("payPlanModel")
public class PayPlanModelImpl implements PayPlanModel {
    @Resource
    private PayPlanDao payPlanDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PayPlanSubDataModel payPlanSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;

    @Override
    public Integer insert(PayPlanEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = payPlanDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return success;
    }

    @Override
    public Integer update(PayPlanEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = payPlanDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity, false);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        insertDTO.getSource().remove("creatorId");
        paasEsModel.update(insertDTO);
        paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<PayPlanEntityExt> findEntitys(Map<String, Object> param) {
        List<PayPlanEntityExt> entitys = payPlanDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return payPlanDao.getEntitysCount(param);
    }

    @Override
    public Integer save(PayPlanEntityExt payPlanEntity) throws XbbException {
        if (payPlanEntity.getId() == null || Objects.equals(0L, payPlanEntity.getId())) {
            payPlanEntity.setId(null);
            return insert(payPlanEntity);
        }
        return update(payPlanEntity);
    }

    @Override
    public PayPlanEntityExt getByKey(Long key, String corpid) {
        PayPlanEntityExt entityExt = payPlanDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return entityExt;
    }

    @Override
    public  List<PayPlanEntityExt>  insertBatch(List<PayPlanEntityExt> list) throws XbbException {
        for (PayPlanEntityExt entity : list) {
            paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(list);
        payPlanDao.insertBatch(list);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PayPlanEntityExt item : list) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(item, paasFormDataEntity);
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN);
            insertList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertList);
        paasFormSubDataModel.insertBatchSubFormData(list, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return list;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        // TODO: 2020/9/22
        return updateBatch(list, corpid, null);
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = payPlanDao.updateBatch(list, corpid);
            if (refreshPolicy == null) {
                paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
            }else{
                paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAY_PLAN, WriteRequest.RefreshPolicy.NONE);
            }
        }
        // todo
        if (!subList.isEmpty()) {
            payPlanSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }


    @Override
    public Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException {
        Integer integer = payPlanDao.deleteBatch(list, corpid);
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        paasEsModel.delete(deleteDTO);
        Integer integer = payPlanDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return integer;
    }

    @Override
    public Integer updateBatchForData(List<? extends PaasFormDataEntity> list, String corpid) throws XbbException {
        for (PaasFormDataEntity paasFormDataEntityExt : list) {
            paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(list);
        Integer updateCount = payPlanDao.updateBatchForAll(list,corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity entityExt : list){
            InsertDTO insertDTO = new InsertDTO();
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entityExt, paasFormDataEntity);
            insertDTO.setEsId(corpid+"_"+entityExt.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        // todo
        return updateCount;
    }

    @Override
    public List<AiPayPlanEntity> getPayPlanList4Ai(String corpid, List<Long> idIn) {
        return payPlanDao.getPayPlanList4Ai(corpid, idIn);
    }

    /**
     * Description: 脚本使用  根据合同id获取逾期的付款计划
     *
     * @param corpid            公司id
     * @param purchaseIds       合同id
     * @param startEstimateTime 查询的预计付款时间（开始）
     * @param endEstimateTime   查询的预计付款时间（结束）
     * @return java.util.List<com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt>
     * @author chenshan
     * @date 2019/4/4 17:29
     * @since v1.0
     */
    @Override
    public List<PayPlanEntityExt> getPayPlanOverdueByPurchaseId(String corpid, List<Long> purchaseIds, Long startEstimateTime, Long endEstimateTime) {
        List<PayPlanEntityExt> entityExts = payPlanDao.getPayPlanRemindByPurchaseId(corpid, purchaseIds, startEstimateTime, endEstimateTime);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return entityExts;
    }

    /**
     * Description: (脚本使用) 根据采购合同id获取即将逾期的付款计划
     *
     * @param corpid      公司id
     * @param purchaseIds 采购合同id
     * @param startTime   查询的到期时间（开始）
     * @param endTime     查询的到期时间（结束）
     * @return java.util.List<com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt>
     * @author chenshan
     * @date 2020/3/6 17:29
     * @since v1.0
     */
    @Override
    public List<PayPlanEntityExt> getPayPlanRemindByPurchaseId(String corpid, List<Long> purchaseIds, Long startTime, Long endTime) {
        List<PayPlanEntityExt> entityExts = payPlanDao.getPayPlanRemindByPurchaseId(corpid, purchaseIds, startTime, endTime);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return entityExts;
    }


    @Override
    public List<PayPlanEntityExt> getPayPlanByIdIn(String corpid,List<Long> payPlanIdIn){
        List<PayPlanEntityExt> entityExts = payPlanDao.getPayPlanByIdIn(corpid, payPlanIdIn);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PAY_PLAN_SUB);
        return entityExts;
    }

    @Override
    public List<PayPlanEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return payPlanDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        String status = FastJsonHelper.getStringOrDefaultFromFormData(dataEntity.getData(), PayPlanEnum.STATUS.getAttr(), "");
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(status, PayPlanStatusEnum.UN_RECEIVABLES.getCode())) {
                if (PayPlanEnum.unReceiveDisableEdit(attr)) {
                    fieldAttrEntity.setEditable(0);
                }
                if (Objects.equals(attr, PayPlanEnum.STATUS.getAttr())) {
                    fieldAttrEntity.getItems().removeIf(item -> Objects.equals(item.getShowType(), ShowTypeEnum.EXCLUDE_NEW.getCode()));
                }
            } else {
                if (PayPlanEnum.disableEdit(attr)) {
                    fieldAttrEntity.setEditable(0);
                }
            }
            if (Objects.equals(attr, PayPlanEnum.ESTIMATE_TIME.getAttr()) && Objects.equals(status, PayPlanStatusEnum.RECEIVABLES.getCode())) {
                // 已收款的预计回款时间不能编辑
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonObject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, PayPlanEnum.LINK_SUPPLIER.getAttr(), PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr(), PayPlanEnum.LINK_SUPPLIER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PayPlanEnum.LINK_PURCHASE.getAttr(), PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(), PayPlanEnum.LINK_PURCHASE.getFieldType());

    }


    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = payPlanDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN);
        paasEsModel.update(insertDTO);
        return success;
    }
}
